package com.fmboy.MXH.nav.handler;

import com.fmboy.MXH.nav.domain.Result.Result;
import jakarta.xml.bind.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    // 公共的错误处理方法
    private ResponseEntity<Result<?>> buildErrorResponse(Exception ex, String message, HttpStatus status) {
        Result<?> result = Result.error(message);
        log.error("{}: {}", message, ex.getMessage());
        return new ResponseEntity<>(result, status);
    }

    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<Result<?>> handleValidationException(
            ValidationException ex, WebRequest request) {
        return buildErrorResponse(ex, "参数验证错误：" + ex.getMessage(), HttpStatus.BAD_REQUEST);
    }

    // 超出最大上传大小
    @ExceptionHandler(org.springframework.web.multipart.MaxUploadSizeExceededException.class)
    public ResponseEntity<Result<?>> handleMaxUploadSizeExceededException(
            org.springframework.web.multipart.MaxUploadSizeExceededException ex, WebRequest request) {
        return buildErrorResponse(ex, "文件大小超过2M，请重新上传", HttpStatus.BAD_REQUEST);
    }

    // 数据库报错
    @ExceptionHandler(org.springframework.dao.DataAccessException.class)
    public ResponseEntity<Result<?>> handleDataAccessException(
            org.springframework.dao.DataAccessException ex, WebRequest request) {
        return buildErrorResponse(ex, "数据库错误，请稍后再试或联系管理员", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 空指针异常
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<Result<?>> handleNullPointerException(
            NullPointerException ex, WebRequest request) {
        return buildErrorResponse(ex, "空指针异常，请稍后再试", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 类型转换异常处理：如从 String 转换到 Integer 失败
    @ExceptionHandler(TypeMismatchException.class)
    public ResponseEntity<Result<?>> handleTypeMismatchException(
            TypeMismatchException ex, WebRequest request) {
        return buildErrorResponse(ex, "参数类型不匹配，无法转换为指定类型", HttpStatus.BAD_REQUEST);
    }

    // 处理通用异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Result<?>> handleAllExceptions(
            Exception ex, WebRequest request) {
        return buildErrorResponse(ex, "服务器内部错误，请稍后再试或联系管理员", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
